package org.wawa.tools.codegenerator.utils;

import lombok.Data;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @author kevin
 * @date 2020/05/28
 */
public class FileUtils {

    /**
     * 获取文件夹下所有的文件路径
     *
     * @param dirPath
     * @return 是否相对路径
     */
    public static List<PathModel> getDirBottomFilePaths(String dirPath, boolean isRelativePath) {
        List<PathModel> result = new ArrayList<>();
        //String filename = "/Users/kevin/Documents/code/gitee/renren-generator/src/main/resources/code-templates/one/";
        String targetDirPath = dirPath;
        File targetFile = new File(dirPath);

        if (isRelativePath) {
            targetDirPath = Thread.currentThread().getContextClassLoader().getResource(dirPath).getFile();
            targetFile = new File(targetDirPath);
        }

        List<String> paths = new ArrayList<>();
        getBottomFilePaths(targetFile, paths);

        for (String path : paths) {
            PathModel pm = new PathModel();

            pm.setPath(path);
            pm.setRelativePath(path.replace(targetDirPath, ""));
            pm.setRelativeDir(dirPath);
            pm.setAbsolutePath(path);
            pm.setAbsoluteDir(targetDirPath);

            if (isRelativePath) {
                pm.setPath(pm.getRelative2Path());
            }
            result.add(pm);
        }

        return result;
    }

    private static void getBottomFilePaths(File file, List<String> paths) {
        File[] fs = file.listFiles();
        if (fs == null) {
            System.out.println("不存在 --> " + file.getPath());
            return;
        }
        for (File f : fs) {
            if (f.isDirectory()) {    //若是目录，则递归打印该目录下的文件
                getBottomFilePaths(f, paths);
            }

            if (f.isFile()) {    //若是文件，直接打印
                //System.out.println(f);
                f.getAbsolutePath();
                paths.add(f.getPath());
            }
        }
    }

    @Data
    public static class PathModel {
        /**
         * 路径
         */
        private String path;

        /**
         * 相对与相对目录的相对路径
         */
        private String relativePath;

        /**
         * 相对路径对应的目录
         */
        private String relativeDir;

        /**
         * 绝对目录
         */
        private String absoluteDir;

        /**
         * 绝对路径
         */
        private String absolutePath;

        /**
         * @return
         */
        public String getRelative2Path() {
            if (relativeDir.endsWith(File.separator)) {
                return relativeDir + relativePath;
            } else {
                return relativeDir + File.separator + relativePath;
            }
        }

        public String getSubPath(){
            String replace = absolutePath.replace(absoluteDir, "");
            return replace.startsWith(File.separator) ? replace.substring(1) : replace;
        }
    }
}
